<template>
  <div class="chart-item-container">
    <div v-if="loading"></div>
    <div ref="hotProdChart" class="chart-item"></div>
  </div>
</template>
<script setup name="HotProductChart">
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue';
import useEcharts from '/@/utils/useEcharts';
import { usesStatisticsApi } from "/@/api/useAutoApi/statistics";


const loading = ref(true)
const hotProdChart = ref(null);
let chartInstance = null;
let data = reactive([]);

const activityLevel = async () => {
  const fetchData = await usesStatisticsApi().getUserActivityLevel();
  Object.assign(data, fetchData.data);
}
const init = () => {
  const option = {
    grid: {
      top: '2%',
      left: '5%',
      right: '8%',
      bottom: '2%',
      containLabel: true,
    },
    tooltip: {
      trigger: 'axis',
    },
    yAxis: {
      type: 'category',
      data: data.name,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        textStyle: {
          fontSize: 10,
          color: '#98A3B2',
        },
      },
    },
    xAxis: {
      show: false,
    },
    series: [
      {
        type: 'pictorialBar',
        name: '访问次数',
        stack: '指数',
        data: data.total_logins,
        smooth: true,
        symbol: 'rect',
        symbolRepeat: true,
        symbolSize: [2, 10],
        symbolMargin: 1,
        label: {
          show: true, //开启数值显示
          position: 'right', //在上方显示
          textStyle: {
            //数值样式
            color: 'var(--el-color-primary)',
            fontSize: 12,
          },
        },
        itemStyle: {
          color: 'var(--el-color-primary)',
        },
      },
    ],
  }
  nextTick(() => {
    if (hotProdChart.value) {
      chartInstance = useEcharts(hotProdChart.value);

      try {
        chartInstance.setOption(option);
        loading.value = false;
      } catch (error) {
        console.error('设置option失败:', error);
      }
    }
  });
}
const updateChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

onMounted(async  () => {
  await activityLevel()
  init();
})
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
})

defineExpose({
  loading,
  hotProdChart,
  updateChart,
});
</script>

<style lang="scss" scoped>
.chart-item-container {
  .chart-item {
    height: 12vh;
  }
}
</style>
